<template>
<div class="dashboard-container publish-container">
    <div class="app-container">
      <el-card>
        <!-- form表单 -->
        <el-form :inline="true" :model="formInline" class="demo-form-inline">
          <el-form-item label="关键字">
            <el-input v-model="formInline.user"></el-input>
          </el-form-item>
          <el-form-item label="状态">
            <el-select v-model="formInline.state" placeholder="请选择">
              <el-option label="已禁用" :value="0"></el-option>
              <el-option label="已启用" :value="1"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item>
            <el-button  @click="onClear" :loading="isLoading">清除</el-button>
            <el-button type="primary" @click="onSearch" :loading="isLoading">搜索</el-button>
          </el-form-item>
          <el-form-item class="btn">
            <el-button type="success" class="btn" icon="el-icon-edit" @click="addArticle">新增技巧</el-button>
          </el-form-item>
        </el-form>
      <!-- 列表信息 -->
       <!-- <div class="list"><i class="el-icon-info" style="margin-right:10px"></i>数据一共{{total_count}}条</div> -->
       <el-alert
       :title="alertText"
       :closable="false"
       style="margin-bottom:15px"
       type="info"
       show-icon>
      </el-alert>
       <el-table
      :data="list"
      style="width: 100%;">
      <el-table-column
        prop="id"
        label="序号"
        width="80">
      </el-table-column>
      <el-table-column
        label="文章标题"
        width="350">
        <template slot-scope="scope"> 
          <span style="margin-right: 10px">{{ scope.row.title }}
            <i v-if="scope.row.videoURL" class="el-icon-film" @click="watchVideo(scope.row.id)"></i> 
          </span>
        </template> 
      </el-table-column>
      <el-table-column
        prop="visits"
        label="阅读数"
        width="100">
      </el-table-column>
      <el-table-column
        prop="username"
        label="录入人">
      </el-table-column>
      <el-table-column
        label="录入时间">
        <template slot-scope="scope">
          {{scope.row.createTime | parseTimeByString('{y}-{m}-{d}')}}
        </template>
      </el-table-column>
      <el-table-column label="状态">
        <template slot-scope="scope">
                <!-- {{scope.row.status}} -->
                <p v-if="scope.row.state === 1" >已启用</p>
                <p v-else type="danger">已禁用</p>
              </template>
      </el-table-column>
      <el-table-column label="操作">
        <template slot-scope="scope">
          <el-button type="text" @click="watchArticle(scope.row.id)">预览</el-button>
          <el-button type="text"  v-text="scope.row.state === 1? '禁用' : '启用'" @click="hChangeStatus(scope.row.id,scope.row.state)">
            </el-button>
          <el-button type="text" :disabled="scope.row.state===1" @click="articleUpdata(scope.row.id)">修改</el-button>
          <el-button type="text" :disabled="scope.row.state===1" @click="articleDelete(scope.row.id)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    <!-- 分页 -->
    <el-pagination
      background
      style="margin:10px 0px 10px 0px;float:right;"
      @size-change="handleSizeChange"
      @current-change="handleCurrentChange"
      :page-sizes="[10, 20, 30, 40]"
      :page-size="10"
      layout="prev, pager, next, sizes, jumper"
      :total="total_count">
    </el-pagination>
    </el-card>
    <!-- 点击图标 弹出框 弹出视频 -->
    <el-dialog
    :show-close="false"
    custom-class="dialog-hb"
    :visible.sync="dialogVisible"
    >
    <video :src="videoUrl" autoplay="autoplay" loop="loop" controls="controls" class="container">
      </video>
    </el-dialog>
    <!-- 点击预览 弹出框 -->
    <el-dialog title="预览文章" :visible.sync="dialogFormVisible">
      <h2>{{articleTitle}}</h2>
      <p>{{articleTime | parseTimeByString("{y}-{m}-{d}")}} 超级管理员  <i class="el-icon-view"></i> {{articleReads}}</p>
      <div class="article" v-html="articleList"></div>
    </el-dialog>
    <!-- 点击新增技巧 弹出框 -->
    <el-dialog title="新增文章" :visible.sync="dialogArticleVisible" @close="closeArticle">
      <el-form ref="form" :model="form" :rules="rules">
        <el-form-item label="文章标题" :label-width="formLabelWidth" prop="name">
          <el-input v-model="form.name" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="文章内容" :label-width="formLabelWidth" prop="content">
          <quill-editor v-model="form.content" :options="editorOption"></quill-editor>
        </el-form-item>
        <el-form-item label="视频地址" :label-width="formLabelWidth">
          <el-input v-model="form.url" autocomplete="off"></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogArticleVisible = false">取 消</el-button>
        <el-button type="primary" @click="hAddArticle">确 定</el-button>
      </div>
    </el-dialog>
    <!-- 点击修改 弹出框 -->
    <el-dialog title="修改文章" :visible.sync="dialogArticleUpdataVisible" @close="closeArticle">
      <el-form ref="form" :model="form" :rules="rules">
        <el-form-item label="文章标题" :label-width="formLabelWidth" prop="name">
          <el-input v-model="form.name" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="文章内容" :label-width="formLabelWidth" prop="content">
          <quill-editor style="height:150px;" v-model="form.content" :options="editorOption"></quill-editor>
        </el-form-item>
        <el-form-item label="视频地址" :label-width="formLabelWidth" style="margin-top:80px;">
          <el-input v-model="form.url" autocomplete="off"></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogArticleUpdataVisible = false">取 消</el-button>
        <el-button type="primary" @click="updataArticle(id)">确 定</el-button>
      </div>
     
    </el-dialog>
    </div>
  </div>
  
</template>

<script>
import { list, detail,add,remove,update,changeState } from "@/api/hmmm/articles"
import 'quill/dist/quill.core.css'
import 'quill/dist/quill.snow.css'
import 'quill/dist/quill.bubble.css'
// 导入组件
import { quillEditor } from 'vue-quill-editor'

export default {
  components: {
    quillEditor
  },
  name: 'Articles',
  data() {
    return {
      alertText: '', // 提示框的内容
      isLoading: false, // loading...效果
      list: [], // 列表信息
      total_count: 0, // 列表的总条数
      formInline: {
        user: '',
        state: null
      },
      requestParameters: {
        page: 1, // 当前页码数为1
        pagesize: 10,
        keyword: '', // 关键字
        state: '' // 状态
      },
      videoUrl: '', // 小图标的视屏链接
      dialogVisible: false, // 视屏的弹出框显示
      dialogFormVisible: false, // 浏览弹出框的设置
      dialogArticleVisible:false, // 新增文章的弹出框
      dialogArticleUpdataVisible: false, // 修改文章的弹出框
      articleList: '', // 预览文章的内容
      articleTitle: '', // 预览文章的标题
      articleTime: '', // 预览文章的录入时间
      // articleUsername: '', // 预览文章的录入人
      articleReads: '', // 预览文章的阅读数
      form: {
        name: '', // 新增技巧的标题 
        content: '', // 新增技巧的内容
        url: '' // 新增技巧的地址
      },
      articleState:{
        id: '',
        state: ''
      },
      id: null,
      formLabelWidth: '120px',
      // 表单验证 
      rules: {
        name: [
          { required: true, message: '请输入文章标题', trigger: 'blur' },
        ],
        content: [
          { required: true, message: '请输入文章内容', trigger: 'blur' },
        ]
      },
      editorOption: {
        placeholder: '',
        modules: {
        // 配置工具栏
          toolbar: [
            ['bold', 'italic', 'underline', 'strike'],
            ['blockquote', 'code-block'],
            [{ header: 1 }, { header: 2 }],
            [{ list: 'ordered' }, { list: 'bullet' }],
            [{ indent: '-1' }, { indent: '+1' }],
            ['image']
          ]
        }
      }
    }
  },
  created () {
    this.getList()
  },
  methods: {
    // 修改文章
    async articleUpdata (id) { // if (id) {}
      this.dialogArticleUpdataVisible = true
      const { data: res} = await detail({ id:id })
      console.log(res)
      this.form.name = res.title
      this.form.content = res.articleBody
      this.form.id = res.id
      console.log(this.form.id)
    },
    // 点击保存按钮，确定修改文章
    updataArticle (id) {
      console.log('这是', this.form.id)
      this.$refs.form.validate(result => {
        console.log(result)
        // 验证通过
        if (result) {
          this.doUpdataArticle(this.form.id)
        }
      })
    },
    async doUpdataArticle (id) {
      console.log('shishis', id)
      const { data :res } = await update({
        id:id,
        title: this.form.name,
        articleBody: this.form.content
      })
      console.log(res) 
      this.dialogArticleUpdataVisible = false
      this.$message.success('修改成功')
      this.getList()
    },
    // 删除文章
    articleDelete (id) {
      console.log(id)
      this.$confirm('此操作将永久删除该文章, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(async () => {
        const { data : res } = await remove({ id: id })
        this.getList ()
        this.$message({
          type: 'success',
          message: '删除成功!'
        });
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消删除'
         })
       })  
    },
    // 浏览文章
    async watchArticle (id) {
      this.dialogFormVisible = true
      const { data: res} = await detail({id:id})
      this.articleList = res.articleBody
      this.articleTitle = res.title
      this.articleTime = res.createTime
      // this.articleUsername = res.username
      this.articleReads = res.visits
    },
    // 点击小图标播放视频
    watchVideo (id) {
      this.dialogVisible = true
      console.log(id)
      // this.videoUrl = list.videoURL
      this.videoUrl = this.list.filter(i => i.id === id)[0].videoURL
      // 过滤list 如果list中有和传入的id一样的  就返回到一个新数组中 id是唯一值 所以返回的新数组只有一项 取第0项 获取视频地址
      console.log(this.videoUrl)
    },
    // 获取列表数据
    async getList () {
      const { data: res } = await list({
        page : this.requestParameters.page,
        pagesize:this.requestParameters.pagesize
        })
      this.list = res.items
      console.log(res)
      this.total_count = res.counts
       
      this.alertText = `数据一共${res.counts}条`
    },
    // 新增技巧
    addArticle () {
      console.log('submit!')
      this.dialogArticleVisible = true
      this.$refs.form.validate(result => {
        console.log(result)
        // 验证通过
        if (result) {
          this.hAddArticle()
        }
      })
    },
    // 点击确定按钮 提交数据
    async hAddArticle () {
      this.requestParameters.title =this.form.name
      this.requestParameters.articleBody = this.form.content
      const  { data : res } = await add(this.requestParameters)
      console.log(res)
      this.dialogArticleVisible = false
      this.$message.success('添加成功')
      this.getList()
    },
    // 清空新增技巧弹出框的内容 因为在data中赋值为空  后边点击修改就会给表单赋值，所以需要每次清空一下
    closeArticle () {
      console.log(11111)
      this.$refs.form.resetFields()
    },
    // 设置分页 每页显示几条
    handleSizeChange(val) {
      console.log(`每页 ${val} 条`)
      this.requestParameters.pagesize = `${val}`
      console.log(this.requestParameters.pagesize)
      this.getList()
    },
    // 分页功能
    handleCurrentChange(val) {
      console.log(`当前页: ${val}`)
      // 刷新页码
      this.requestParameters.page = `${val}`
      // 重新渲染列表
      this.getList()
    },
    // 清除表单
    onClear () {
      this.formInline.user = ''
      this.formInline.state = ''
      this.getList()
    },
    // 表单搜索功能
    async onSearch () {
      this.isLoading = true
      this.requestParameters.keyword = this.formInline.user
      this.requestParameters.state = this.formInline.state
      const { data: res } = await list(this.requestParameters)
      this.list = res.items
      this.total_count = res.counts
      this.isLoading = false
    },
    // 启用和禁用
    async hChangeStatus (index,row) {
      console.log(index, row)
      if (row === 0) {
        row = 1
      } else if (row === 1) {
        row = 0
      }
      this.d.id = index
      this.articleState.state = row
      const rsult = await changeState(this.articleState)
      this.$message.success('操作成功')
      this.getList()
    }
  }
}
</script>

<style scoped rel="stylesheet/scss" lang="scss">
.btn {
  float: right;
}
.container {
  width:100%;
}
::v-deep .dialog-hb{
  background: transparent !important;
}
::v-deep .dialog-hb .el-dialog__header{
  background: transparent !important;
}
.article {
  background: #F5F5F5;
  padding:10px 10px;
  border-top: 1px dashed #ccc;
}
.publish-container ::v-deep .ql-editor{
  height: 150px;
}
</style>
